package jnpf.controller;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.base.service.BillRuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.UserInfo;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import org.springframework.transaction.annotation.Transactional;
import jnpf.base.entity.ProvinceEntity;
import jnpf.model.whu_learningcollection.*;
import jnpf.model.whu_learningcollection.Whu_learningcollectionPagination;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.service.UserService;
import jnpf.model.whu_learningcollection.Whu_learningcollectionCrForm;
import jnpf.model.whu_learningcollection.Whu_learningcollectionInfoVO;
import jnpf.model.whu_learningcollection.Whu_learningcollectionListVO;
import jnpf.model.whu_learningcollection.Whu_learningcollectionUpForm;
import jnpf.entity.*;
import jnpf.base.service.ProvinceService;
import jnpf.util.*;
import jnpf.base.util.*;
import jnpf.base.vo.ListVO;
import jnpf.util.context.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jnpf.entity.Whu_learningcollectionEntity;
import jnpf.service.Whu_learningcollectionService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


/**
 *
 * whu_learningcollection
 * @版本： V3.2.0
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-06-10
 */
@Slf4j
@RestController
@Api(tags = "whu_learningcollection" , value = "example")
@RequestMapping("/api/example/Whu_learningcollection")
public class Whu_learningcollectionController {


    @Autowired
    private DynDicUtil dynDicUtil;
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private UserProvider userProvider;

    @Autowired
    private Whu_learningcollectionService whu_learningcollectionService;



    /**
     * 列表
     *
     * @param whu_learningcollectionPagination
     * @return
     */
	@PostMapping("/getList")
    public ActionResult list(@RequestBody Whu_learningcollectionPagination whu_learningcollectionPagination)throws IOException{
        List<Whu_learningcollectionEntity> list= whu_learningcollectionService.getList(whu_learningcollectionPagination);
        //处理id字段转名称，若无需转或者为空可删除
    for(Whu_learningcollectionEntity entity:list){
                    entity.setType(dynDicUtil.getDicName(entity.getType()));
        entity.setUserid(generaterSwapUtil.userSelectValue(entity.getUserid()));
    }
	List<Whu_learningcollectionListVO> listVO=JsonUtil.getJsonToList(list,Whu_learningcollectionListVO.class);
    for(Whu_learningcollectionListVO whu_learningcollectionVO:listVO){
            }



        PageListVO vo=new PageListVO();
        vo.setList(listVO);
        PaginationVO page=JsonUtil.getJsonToBean(whu_learningcollectionPagination,PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }


    /**
     * 创建
     *
     * @param whu_learningcollectionCrForm
     * @return
     */
    @PostMapping
    @Transactional
    public ActionResult create(@RequestBody @Valid Whu_learningcollectionCrForm whu_learningcollectionCrForm) throws DataException {
        String mainId =RandomUtil.uuId();
        UserInfo userInfo=userProvider.get();
        whu_learningcollectionCrForm.setTodate(DateUtil.getNow());
        whu_learningcollectionCrForm.setUserid(userInfo.getUserId());
        Whu_learningcollectionEntity entity = JsonUtil.getJsonToBean(whu_learningcollectionCrForm, Whu_learningcollectionEntity.class);
				entity.setId(mainId);
                whu_learningcollectionService.save(entity);


        return ActionResult.success("创建成功");
}



    /**
    * 模板下载
    *
    * @return
    */
    @ApiOperation("模板下载")
    @GetMapping("/templateDownload")
    public ActionResult<DownloadVO>  TemplateDownload(){
        UserInfo userInfo=userProvider.get();
        DownloadVO vo=DownloadVO.builder().build();
        try{
            vo.setName("职员信息.xlsx");
            vo.setUrl(UploaderUtil.uploaderFile("/api/Common/DownloadModel?encryption=" ,userInfo.getId()+"#"+"职员信息.xlsx"+"#"+"Temporary"));
        }catch(Exception e){
            log.error("信息导出Excel错误:{}" ,e.getMessage());
        }
        return ActionResult.success(vo);
    }
    /**
    * 导出Excel
    *
    * @return
    */
    @ApiOperation("导出Excel")
    @GetMapping("/Actions/Export")
    public ActionResult Export(Whu_learningcollectionPaginationExportModel whu_learningcollectionPaginationExportModel) throws IOException {
        Whu_learningcollectionPagination whu_learningcollectionPagination=JsonUtil.getJsonToBean(whu_learningcollectionPaginationExportModel, Whu_learningcollectionPagination.class);
        List<Whu_learningcollectionEntity> list=  whu_learningcollectionService.getTypeList(whu_learningcollectionPagination,whu_learningcollectionPaginationExportModel.getDataType());
        //处理id字段转名称，若无需转或者为空可删除
    for(Whu_learningcollectionEntity entity:list){
                    entity.setType(dynDicUtil.getDicName(entity.getType()));
        entity.setUserid(generaterSwapUtil.userSelectValue(entity.getUserid()));
    }
	List<Whu_learningcollectionListVO> listVO=JsonUtil.getJsonToList(list,Whu_learningcollectionListVO.class);
    for(Whu_learningcollectionListVO whu_learningcollectionVO:listVO){
            }


        //转换为map输出
        List<Map<String, Object>>mapList=JsonUtil.getJsonToListMap(JsonUtil.getObjectToStringDateFormat(listVO,"yyyy-MM-dd HH:mm:ss"));
        String[]keys=!StringUtil.isEmpty(whu_learningcollectionPaginationExportModel.getSelectKey())?whu_learningcollectionPaginationExportModel.getSelectKey().split(","):new String[0];
        UserInfo userInfo=userProvider.get();
        DownloadVO vo=creatModelExcel(configValueUtil.getTemporaryFilePath(),mapList,keys,userInfo);
        return ActionResult.success(vo);
    }
    //导出表格
    public static DownloadVO creatModelExcel(String path,List<Map<String, Object>>list,String[]keys,UserInfo userInfo){
        DownloadVO vo=DownloadVO.builder().build();
        try{
            List<ExcelExportEntity> entitys=new ArrayList<>();
            if(keys.length>0){
                for(String key:keys){
                    switch(key){
                    case "todate" :
                    entitys.add(new ExcelExportEntity("收藏时间" ,"todate"));
                    break;
                    case "type" :
                    entitys.add(new ExcelExportEntity("资料类别" ,"type"));
                    break;
                    case "name" :
                    entitys.add(new ExcelExportEntity("资料名称" ,"name"));
                    break;
                    case "url" :
                    entitys.add(new ExcelExportEntity("资料链接" ,"url"));
                    break;
                    case "userid" :
                    entitys.add(new ExcelExportEntity("用户id" ,"userid"));
                    break;
            default:
                    break;
                    }
                }
            }
            ExportParams exportParams = new ExportParams(null, "表单信息");
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMddHHmmss") + ".xls";
            vo.setName(fileName);
            vo.setUrl(UploaderUtil.uploaderFile(userInfo.getId() + "#" + fileName + "#" + "Temporary"));
            path =path+fileName;
            FileOutputStream fos = new FileOutputStream(path);
            workbook.write(fos);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return vo;
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchRemove/{ids}")
    @Transactional
    public ActionResult batchRemove(@PathVariable("ids") String ids){
        String[] idList = ids.split(",");
		int i =0;
        for (String allId : idList){
            this.delete(allId);
            i++;
        }
        if (i == 0 ){
            return ActionResult.fail("删除失败");
        }
            return ActionResult.success("删除成功");
    }



    /**
    * 信息
    *
    * @param id
    * @return
    */
    @GetMapping("/{id}")
    public ActionResult<Whu_learningcollectionInfoVO> info(@PathVariable("id") String id){
        Whu_learningcollectionEntity entity= whu_learningcollectionService.getInfo(id);
        Whu_learningcollectionInfoVO vo=JsonUtil.getJsonToBean(entity, Whu_learningcollectionInfoVO.class);
        if(vo.getTodate()!=null){
            vo.setTodate(vo.getTodate());
        }
        if(StringUtil.isNotEmpty(entity.getUserid())){
				UserEntity userEntity=userService.getInfo(entity.getUserid());
				vo.setUserid(userEntity.getRealName()+"/"+userEntity.getAccount());
        }

        return ActionResult.success(vo);
    }





   /**
    * 更新
    *
    * @param id
    * @return
    */
    @PutMapping("/{id}")
    @Transactional
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid Whu_learningcollectionUpForm whu_learningcollectionUpForm) throws DataException {
        UserInfo userInfo=userProvider.get();
        Whu_learningcollectionEntity entity= whu_learningcollectionService.getInfo(id);
        if(entity!=null){
            Whu_learningcollectionEntity subentity=JsonUtil.getJsonToBean(whu_learningcollectionUpForm, Whu_learningcollectionEntity.class);
					subentity.setTodate(entity.getTodate());
					subentity.setUserid(entity.getUserid());
            whu_learningcollectionService.update(id, subentity);
        return ActionResult.success("更新成功");
        }else{
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

   /**
    * 删除
    *
    * @param id
    * @return
    */
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id){
        Whu_learningcollectionEntity entity= whu_learningcollectionService.getInfo(id);
        if(entity!=null){
            whu_learningcollectionService.delete(entity);

        }
        return ActionResult.success("删除成功");
    }


}
